<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      width="80%"
      align-center
      :show-close="false"
      @close="handleClose"
      destroy-on-close
      draggable
    >
      <template #header="{ close }">
        <div class="dialog-header flex justify-between items-center">
          <div>{{ title }}</div>
          <el-icon class="el-icon--left cursor-pointer" @click="close"
            ><CircleCloseFilled color="#fff"
          /></el-icon>
        </div>
      </template>
      <!-- 项目信息 -->
      <ProjectInfo :projectId="projectId" />
      <!-- 基本信息 -->
      <div class="bg-white my-[10px]">
        <BaseHead>基本信息</BaseHead>
        <div class="p-[10px]">
          <el-form :model="editForm" :rules="rules" label-width="130px" ref="editFormRef">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item prop="fileId" label="中检报告">
                  <FileUpload
                    class="flex-1"
                    :uploadUrl="uploadUrl"
                    v-model="fileList"
                    @change="fileChange"
                    :limit="1"
                    tip="附件大小不超过20M"
                    exceedLimitType="disabled"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="middleCheckDate" label="中检日期">
                  <el-date-picker
                    v-model="editForm.middleCheckDate"
                    type="date"
                    placeholder="请选择日期"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item prop="note" label="中检说明">
                  <el-input
                    type="textarea"
                    v-model="editForm.note"
                    placeholder="请输入中检说明"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <div class="operate-btns">
            <!-- <template v-if="verifyRoleType.isKyry()">
              <el-button type="primary" @click="save(-1)" :loading="loading">暂存</el-button>
              <el-button type="primary" @click="save(1)" :loading="loading">提交</el-button>
            </template>
            <template v-if="verifyRoleType.iskycgly()">
              <el-button type="primary" @click="save(-1)" :loading="loading">保存</el-button>
              <el-button
                type="primary"
                @click="save(2)"
                v-if="[-1, 3].includes(Number(checkStatus)) || editForm.isAuditor"
                :loading="loading"
                >保存并通过</el-button
              >
            </template> -->
            <el-button
              type="primary"
              @click="save(-1)"
              :loading="loading && submitType == -1"
              :disabled="loading && submitType != -1"
              >{{ verifyRoleType.isKyry() ? "暂存" : "保存" }}</el-button
            >
            <el-button
              type="primary"
              @click="save(1)"
              :loading="loading && submitType == 1"
              :disabled="loading && submitType != 1"
              v-if="verifyRoleType.isKyry()"
              >提交</el-button
            >
            <el-button
              type="primary"
              @click="save(2)"
              v-if="
                verifyRoleType.iskycgly() &&
                ([-1, 3].includes(Number(checkStatus)) || editForm.isAuditor)
              "
              :loading="loading && submitType == 2"
              :disabled="loading && submitType != 2"
              >保存并通过</el-button
            >
            <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import ProjectInfo from "./ProjectInfo.vue";
import FileUpload from "@/views/project/components/FileUpload.vue";
import { addRecords, editRecords, recordsDetail } from "@/api/project/zx/xmzj";
import { ElMessage } from "element-plus";
import { assignObj, verifyRoleType } from "@/utils/main";
const uploadUrl = `/commonFile/uploadFile?modelName=项目中检`;
const dialogVisible = ref(false);
const editFormRef = ref();
const detailData = ref({});
const fileList = ref([]);
const operateId = ref(null);
const projectClass = ref("");
const projectType = ref("");
const projectId = ref("");
const checkStatus = ref(""); //审核状态
const title = computed(() => {
  return operateId.value ? "中检编辑" : "中检新增";
});
const loading = ref(false);
const submitType = ref(null);
const editForm = reactive({
  fileId: "",
  middleCheckDate: "",
  note: "",
  taskId: "", //任务id
  isAuditor: "", //当前是否能审核
  checkstatus: "",
});
const rules = {
  fileId: [
    {
      required: true,
      message: "请上传中检报告",
    },
  ],
};
//获取记录详情
const getDetail = async () => {
  try {
    const res = await recordsDetail(operateId.value);
    detailData.value = res.data;
    checkStatus.value = detailData.value.checkstatus;
    projectClass.value = detailData.value.projectClass;
    projectType.value = detailData.value.projectType;
    if (detailData.value.fileId) {
      fileList.value.push({
        name: detailData.value.fileName,
        id: detailData.value.fileId,
      });
    }
  } catch (error) {
    console.log(error);
  }
};
// 新增
const add = (proClass, proType, proId) => {
  operateId.value = null;
  projectClass.value = proClass;
  projectType.value = proType;
  projectId.value = proId;
  dialogVisible.value = true;
};
// 编辑
const edit = async (id, proId, taskId, isAuditor) => {
  operateId.value = id;
  projectId.value = proId;
  dialogVisible.value = true;
  nextTick(async () => {
    await getDetail();
    //表单表格赋值
    assignObj(editForm, detailData.value);
    //放在assignObj后面 避免值被detailData.value里面的值覆盖掉
    editForm.taskId = taskId;
    editForm.isAuditor = isAuditor;
  });
};
defineExpose({ add, edit });
//上传附件改变
const fileChange = () => {
  const ids = fileList.value.map((item) => {
    const id = item.response ? item.response.data : item.id;
    return id;
  });
  editForm.fileId = ids.join(",");
};
const emit = defineEmits(["save-success"]);
//点击保存
const save = async (type) => {
  try {
    submitType.value = type;
    await editFormRef.value?.validate(async (valid) => {
      if (valid) {
        let res;
        let params = {
          ...editForm,
          projectClass: projectClass.value,
          projectType: projectType.value,
          projectId: projectId.value,
          submitType: type,
        };
        loading.value = true;
        if (operateId.value) {
          params.id = operateId.value;
          res = await editRecords(params);
        } else {
          res = await addRecords(params);
        }
        if (res.code === 200) {
          ElMessage({
            message: "操作成功！",
            type: "success",
          });
          dialogVisible.value = false;
          emit("save-success");
        }
      }
    });
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};
//关闭弹窗
const handleClose = () => {
  //重置基本信息表单数据
  editFormRef.value.resetFields();
  projectClass.value = "";
  projectType.value = "";
  projectId.value = "";
  checkStatus.value = "";
  editForm.taskId = "";
  editForm.isAuditor = "";
  editForm.checkstatus = "";
  fileList.value = [];
  loading.value = false;
};
</script>

<style scoped lang="scss">
@import url("@/views/project/index.scss");
</style>
